package com.aiwu.memory;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiwu.library.util.DisplayUtil;
import com.aiwu.library.util.ToastUtil;
import com.aiwu.widget.FocusConstraintLayout;

import org.citra.citra_emu.R;

import java.lang.ref.WeakReference;

public class KeyboardFragment extends BaseLazyFragment implements View.OnClickListener {
    public static final String EXTRA_SEARCH = "extra_search";
    private WeakReference<EditText> bindEditText;
    private ImageView ivSearch;
    private ViewGroup viewRoot;
    private View keyClose;
    private boolean search = true;

    @Override
    protected void lazyLoad() {
        Bundle arg = getArguments();
        if (arg != null) {
            search = arg.getBoolean(EXTRA_SEARCH, true);
        }
        int paddingLeft, paddingRight, paddingV;
        if (search) {
            if (DisplayUtil.isPortrait()) {
                paddingLeft = paddingRight = getResources().getDimensionPixelOffset(R.dimen.qb_px_45);
            } else {
                paddingLeft = getResources().getDimensionPixelOffset(R.dimen.qb_px_15);
                paddingRight = getResources().getDimensionPixelOffset(R.dimen.qb_px_45);
            }
            paddingV = getResources().getDimensionPixelOffset(R.dimen.qb_px_30);
            viewRoot.setBackground(null);
        } else {
            paddingLeft = paddingRight = getResources().getDimensionPixelOffset(R.dimen.qb_px_30);
            paddingV = getResources().getDimensionPixelOffset(R.dimen.qb_px_45);
            if (DisplayUtil.isPortrait()) {
                viewRoot.setBackgroundResource(R.drawable.emu_lib_shape_corners_8_09101d);
            } else {
                viewRoot.setBackground(null);
            }
        }
        if (viewRoot instanceof FocusConstraintLayout) {
            ((FocusConstraintLayout) viewRoot).setInterceptFocusOut(!search);
        }
        viewRoot.setPadding(paddingLeft, paddingV, paddingRight, paddingV);
        ivSearch.setImageResource(search ? R.drawable.ic_keyboard_search : R.drawable.ic_keyboard_modify);
        if (!viewRoot.isInTouchMode()) {
            //焦点
            keyClose.requestFocus();
        }
    }

    @Override
    protected Boolean repeatedLoad() {
        return true;
    }

    @Override
    protected int initContentView() {
        return R.layout.fragment_keyboard;
    }

    @Override
    protected void initView(View view) {
        view.findViewById(R.id.num_1).setOnClickListener(this);
        view.findViewById(R.id.num_2).setOnClickListener(this);
        view.findViewById(R.id.num_3).setOnClickListener(this);
        view.findViewById(R.id.num_4).setOnClickListener(this);
        view.findViewById(R.id.num_5).setOnClickListener(this);
        view.findViewById(R.id.num_6).setOnClickListener(this);
        view.findViewById(R.id.num_7).setOnClickListener(this);
        view.findViewById(R.id.num_8).setOnClickListener(this);
        view.findViewById(R.id.num_9).setOnClickListener(this);
        view.findViewById(R.id.num_0).setOnClickListener(this);
        view.findViewById(R.id.num_delete).setOnClickListener(this);
        view.findViewById(R.id.num_point).setOnClickListener(this);
        view.findViewById(R.id.num_negative).setOnClickListener(this);
        keyClose = view.findViewById(R.id.num_close);
        keyClose.setOnClickListener(this);
        view.findViewById(R.id.num_search).setOnClickListener(this);
        ivSearch = view.findViewById(R.id.iv_search);
        viewRoot = (ViewGroup) view;
        //屏蔽点击事件
        viewRoot.setOnTouchListener((v, event) -> true);
    }

    /**
     * 绑定EditText
     *
     * @param editText
     */
    public void bindEditText(EditText editText) {
        bindEditText = new WeakReference<>(editText);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.num_1:
            case R.id.num_2:
            case R.id.num_3:
            case R.id.num_4:
            case R.id.num_5:
            case R.id.num_6:
            case R.id.num_7:
            case R.id.num_8:
            case R.id.num_9:
            case R.id.num_0:
                if (v instanceof TextView) {
                    inputNum(((TextView) v).getText().toString());
                }
                break;
            case R.id.num_delete:
                deleteNum();
                break;
            case R.id.num_point:
                inputPoint();
                break;
            case R.id.num_negative:
                inputNegative();
                break;
            case R.id.num_close:
                closeKeyboard();
                break;
            case R.id.num_search:
                if (search) {
                    searchMemory();
                } else {
                    modifyMemory();
                }
                break;
        }
    }

    /**
     * 输入小数点
     */
    private void inputPoint() {
        if (bindEditText != null) {
            EditText editText = bindEditText.get();
            try {
                StringBuilder sb = new StringBuilder(editText.getText());
                int index = editText.getSelectionStart();
                sb.insert(index, ".");
                Float.parseFloat(sb.toString());
                inputNum(".");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 切换正负
     */
    private void inputNegative() {
        if (bindEditText != null) {
            EditText editText = bindEditText.get();
            String strValue = editText.getText().toString();
            String resultStr;
            if (strValue.contains("-")) {
                resultStr = strValue.replace("-", "");
            } else {
                resultStr = "-" + strValue;
            }
            editText.setText(resultStr);
            editText.setSelection(editText.getText().length());
        }
    }

    private void inputNum(String numStr) {
        if (bindEditText != null) {
            EditText editText = bindEditText.get();
            int index = editText.getSelectionStart();
            Editable editable = editText.getText();
            editable.insert(index, numStr);
        }
    }

    private void deleteNum() {
        if (bindEditText != null) {
            EditText editText = bindEditText.get();
            Editable editable = editText.getText();
            if (editable.length() == 0) {
                return;
            }
            int index = editText.getSelectionStart();
            if (index == 0) {
                return;
            }
            editable.delete(index - 1, index);
        }
    }

    private void closeKeyboard() {
        MemoryManager.getInstance().closeKeyboard();
        if (bindEditText != null) {
            EditText editText = bindEditText.get();
            if (editText != null) {
                editText.requestFocus();
            }
        }
    }

    private void searchMemory() {
        if (bindEditText != null) {
            EditText editText = bindEditText.get();
            String strValue = editText.getText().toString();
            if (MemoryManager.isValueValid(strValue)) {
                MemoryManager.getInstance().searchMemoryNormal(strValue);
            } else {
                ToastUtil.toast("输入的值有误，请重新输入");
            }
            cleanEditText();
        }
    }

    public void cleanEditText() {
        if (bindEditText != null) {
            EditText editText = bindEditText.get();
            editText.setText("");
        }
    }

    private void modifyMemory() {
        if (bindEditText != null) {
            EditText editText = bindEditText.get();
            String strValue = editText.getText().toString();
            if (TextUtils.isEmpty(strValue)) {
                ToastUtil.toast("请输入修改的值");
                return;
            }
            if (MemoryManager.isValueValid(strValue)) {
                MemoryManager.getInstance().modifyMemory(strValue);
            } else {
                ToastUtil.toast("输入的值有误，请重新输入");
                editText.setText("");
            }
        }
    }
}
